package a66weding.com.jiehuntong.activity.order;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.PersistableBundle;
import android.os.SystemClock;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.ProgressBar;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.google.gson.Gson;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.xutils.x;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.Serializable;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import a66weding.com.jiehuntong.R;
import a66weding.com.jiehuntong.activity.imageupload.activity.AlbumActivity;
import a66weding.com.jiehuntong.activity.imageupload.activity.GalleryActivity;
import a66weding.com.jiehuntong.activity.imageupload.activity.takephoto.SelectPicPopupWindow;
import a66weding.com.jiehuntong.activity.imageupload.activity.util.Bimp;
import a66weding.com.jiehuntong.activity.imageupload.activity.util.FileUtils;
import a66weding.com.jiehuntong.activity.imageupload.activity.util.ImageItem;
import a66weding.com.jiehuntong.activity.imageupload.activity.util.Res;
import a66weding.com.jiehuntong.activity.me.MeBaseActivity;
import a66weding.com.jiehuntong.activity.me.MeIndentActivity;
import a66weding.com.jiehuntong.application.GlobalApplication;
import a66weding.com.jiehuntong.beans.ErrorBean;
import a66weding.com.jiehuntong.beans.HttpRequestBean;
import a66weding.com.jiehuntong.beans.MyOrderBean;
import a66weding.com.jiehuntong.beans.SuccessBean;
import a66weding.com.jiehuntong.beans.UpLoadImage;
import a66weding.com.jiehuntong.beans.WxremindBean;
import a66weding.com.jiehuntong.common.MessageEvent;
import a66weding.com.jiehuntong.common.utils.CUtils;
import a66weding.com.jiehuntong.common.utils.FileUtil;
import a66weding.com.jiehuntong.common.utils.StrUtil;
import a66weding.com.jiehuntong.common.utils.uploadimage.UpLoadUtil;
import a66weding.com.jiehuntong.http.HttpHandleUtil;
import a66weding.com.jiehuntong.http.NetStatusUtil;
import a66weding.com.jiehuntong.http.OnNetResultListener;
import a66weding.com.jiehuntong.http.RequestCode;

/**
 * 申请售后服务的一级界面
 * Created by Administrator on 2016/9/1.
 */
public class ApplyServiceOneActivity extends MeBaseActivity implements View.OnClickListener, OnNetResultListener {
    private LinearLayout mBackLay;
    private TextView mBackContentTv;
    private TextView mHeaderTitleTv;
    private RelativeLayout mHeaderRightRlay;

    private ScrollView mScrollview;
    private EditText mRealNameEt;
    private EditText mPhoneNumEt;
    private EditText mContentEt;
    private RadioButton mTuihuoRbtn;
    private RadioButton mHuanhuoRbtn;
    private RadioGroup mRadioGroup;
    private ImageButton mSubBtn;
    private ImageButton mAddBtn;
    private TextView mCountTv;
    private TextView mPriceTv;
    private TextView mProductNumTv;
    private TextView mProduct_title;
    private ImageView mPicIv;
    private TextView mSubmitmaxTv;
    private Button mCommitBtn;

    //适配器
    private GridAdapter adapter;
    //gridView
    private GridView evalua_grid;
    //需要动画的pop布局;
    private LinearLayout ll_popup;
    //整体布局
    private LinearLayout ev_group;

    private static final int PICSUCESS = 10;
    private static final int PICERROR = 11;
    public static final int GETPIC = 12;

    private MyOrderBean.DataBean.MyOrderDetailBean myOrderDetailBean;
    private ArrayList<ImageItem> tempSelectBitmapList;
    private PopupWindow pop;
    private static final int TAKE_PICTURE = 0x000001;
    private static final int TAKE_CROP = 3;
    private static int picNums = 0;
    private static int count = 1;
    private StringBuffer picSb = new StringBuffer();
    private boolean iscommitSucess;
    private int commMaxCount;

    private static final int PERMISSION_CAMERA = 5;

    private static final int FINISH = 7;

    private static final int PROGRESS = 8;

    private static int requestCount = 0;

    public static boolean isTakePhoto;

    private PopupWindow mProgresspop;


    Handler handler = new Handler() {
        public void handleMessage(Message msg) {
            Log.e("Log", "GridAdapter handleMessage: msg=" + msg);
            switch (msg.what) {
                case 1:
                    adapter.notifyDataSetChanged();
                    break;
                case PICSUCESS://上传图片成功
                    if(mProgresspop.isShowing()){
                        mProgresspop.dismiss();
                    }

                    commitPinjia();
                    break;
                case PICERROR://上传未完全成功
                    int number = msg.arg1;
                    CUtils.showToast("图片" + number + "上传失败，请重新选择图片上传");
                    if(mProgresspop.isShowing()){
                        mProgresspop.dismiss();
                    }
                    if(mCommitpop.isShowing()){
                        mCommitpop.dismiss();
                    }
                    break;
                case PROGRESS://上传进度
                        if(mProgresspop.isShowing()){
                           int progress = msg.arg1;
                            mProgressbar.setProgress(progress);
                            mProgressTv.setText("正在上传  " +progress+  "%");
                        }
                    break;
                case FINISH:

                    iscommitSucess = true;

                    mCommitBtn.setEnabled(false);
                   try {
                       Activity applyServicePreFirstActivity = ((GlobalApplication) getApplication()).getActivityManager().getActivity("ApplyServiceOneActivity");
                       Activity orderDetailsActivity = ((GlobalApplication) getApplication()).getActivityManager().getActivity("OrderDetailsActivity");
                       if (applyServicePreFirstActivity != null) {
                           applyServicePreFirstActivity.finish();
                       }
                       if (orderDetailsActivity != null) {
                           orderDetailsActivity.finish();
                       }

                       File tempDir = new File(FileUtil.getImgFile(ApplyServiceOneActivity.this), "tuihuan");
                       File[] files = tempDir.listFiles();
                       for (int i = 0; i < files.length; i++) {
                           files[i].delete();
                       }

                   }catch (Exception e){
                   }
                    Intent intent = new Intent(ApplyServiceOneActivity.this, MeIndentActivity.class);
                    startActivity(intent);
                    finish();

                    break;
            }
            super.handleMessage(msg);
        }
    };
    private int buyNumber;
    private ProgressBar mProgressbar;
    private TextView mProgressTv;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_apply_service_one);
        ((GlobalApplication) getApplication()).getActivityManager().addActivity("ApplyServiceOneActivity", this);

        tuihuanActivityMap.put("ApplyServiceOneActivity", this);
        Res.init(this);
        Intent intent = getIntent();
        if (intent != null) {
            myOrderDetailBean = (MyOrderBean.DataBean.MyOrderDetailBean) intent.getSerializableExtra("orderDataBean");
            buyNumber = myOrderDetailBean.getBuyNumber();
            if (myOrderDetailBean.getOrderReturn() != null) {
                commMaxCount = buyNumber - myOrderDetailBean.getOrderReturn().getI_Number();
            } else {
                commMaxCount = buyNumber;
            }

        }

        if (savedInstanceState != null) {
        } else {
        }

        init();

        initview();

        EventBus.getDefault().register(this);
    }

    private void initview() {
        mBackLay = (LinearLayout) findViewById(R.id.llay_header_back);
        mBackContentTv = (TextView) findViewById(R.id.tv_header_backcontent);
        mHeaderTitleTv = (TextView) findViewById(R.id.tv_header_title);
        mHeaderRightRlay = (RelativeLayout) findViewById(R.id.rlay_header_rightfunc);
        ev_group = (LinearLayout) findViewById(R.id.ev_group);

        mScrollview = (ScrollView) findViewById(R.id.scroll_view);
        mRealNameEt = (EditText) findViewById(R.id.et_realName);
        mPhoneNumEt = (EditText) findViewById(R.id.et_phoneNum);
        mContentEt = (EditText) findViewById(R.id.et_desc_content);

        evalua_grid = (GridView) findViewById(R.id.evalua_grid);
        mTuihuoRbtn = (RadioButton) findViewById(R.id.rb_me_pay_2);
        mHuanhuoRbtn = (RadioButton) findViewById(R.id.rb_me_pay_3);
        mRadioGroup = (RadioGroup) findViewById(R.id.rg_me_pay_distrbution_1);

        mSubBtn = (ImageButton) findViewById(R.id.ibtn_sub);
        mAddBtn = (ImageButton) findViewById(R.id.ibtn_add);
        mCountTv = (TextView) findViewById(R.id.tv_count);
        mPriceTv = (TextView) findViewById(R.id.tv_product_price);
        mProductNumTv = (TextView) findViewById(R.id.tv_product_count);
        mPicIv = (ImageView) findViewById(R.id.iv_productPic);
        mProduct_title = (TextView) findViewById(R.id.tv_product_title);
        mSubmitmaxTv = (TextView) findViewById(R.id.tv_maxcount);

        mCommitBtn = (Button) findViewById(R.id.btn_commit);
        mCommitBtn.setEnabled(true);


        mHuanhuoRbtn.setChecked(true);

        mBackContentTv.setText("返回");
        mHeaderTitleTv.setText("申请售后服务");
        mHeaderRightRlay.setVisibility(View.GONE);

        if (myOrderDetailBean != null) {
            double singlePrice = myOrderDetailBean.getSinglePrice();
            float singPrice = StrUtil.floatNumDeal((float) singlePrice);

            mPriceTv.setText("￥ " + singPrice);
            mProductNumTv.setText("x" + String.valueOf(buyNumber));
            x.image().bind(mPicIv, myOrderDetailBean.getProductPicMain());
            mProduct_title.setText(myOrderDetailBean.getProductName());
            mSubmitmaxTv.setText("您最多可提交数量为" + commMaxCount + "个");
            mCountTv.setText(String.valueOf(count));

        }

        mBackLay.setOnClickListener(this);
        mSubBtn.setOnClickListener(this);
        mAddBtn.setOnClickListener(this);
        mCommitBtn.setOnClickListener(this);
        if(!isTakePhoto){
            Bimp.getInstance().getTempSelectBitmap().clear();
            Bimp.max = 0;
        }

        adapter = new GridAdapter(this);
        evalua_grid.setAdapter(adapter);
        adapter.update();
        int measuredHeight = mScrollview.getMeasuredHeight();

        //当点击item的时候进入下一个界面;
        evalua_grid.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                int measuredHeight = mScrollview.getMeasuredHeight();
                if (position == Bimp.getInstance().getTempSelectBitmap().size()) {
                    ll_popup.startAnimation(AnimationUtils.loadAnimation(ApplyServiceOneActivity.this, R.anim.activity_translate_in));
                    pop.showAtLocation(ev_group, Gravity.BOTTOM, 0, 0);
                } else {
                    Intent intent = new Intent(ApplyServiceOneActivity.this,
                            GalleryActivity.class);
                    intent.putExtra("position", "1");
                    intent.putExtra("ID", position);

                    startActivity(intent);
                }
            }
        });


    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.llay_header_back: // 点击返回,关闭界面
                isTakePhoto=false;
                finish();
                //一定要一起用;
                Bimp.getInstance().getTempSelectBitmap().clear();
                Bimp.max = 0;
                break;
            case R.id.ibtn_sub: // 数量减少

                if (count > 1) {
                    count--;
                    mCountTv.setText(String.valueOf(count));
                }
                break;
            case R.id.ibtn_add: // 数量增加

                if (count < commMaxCount) {
                    count++;
                    mCountTv.setText(String.valueOf(count));
                }
                break;
            case R.id.btn_commit: // 提交

                if (iscommitSucess) {
                    CUtils.showToast("您已提交成功了，无需再次提交");
                    return;
                }

                if (checkInfo()) {


                    requestCount = 0;
                    picSb.delete(0, picSb.length());
                    tempSelectBitmapList = Bimp.getInstance().getTempSelectBitmap();
                    if (this.tempSelectBitmapList != null && tempSelectBitmapList.size() > 0) {

                        processBitmap(tempSelectBitmapList);
                        picNums = 0;

                        boolean iswifi = NetStatusUtil.isWifi(this);
                        boolean is4g = NetStatusUtil.is4G(this);
                        if (iswifi || is4g) {
                            updatePics();
                        } else {
                            showDialog();
                        }
                    } else {
                        commitPinjia();
                    }
                }
                break;
        }
    }




    private String commitPinjia() {
        showCommitPopupWindow(ApplyServiceOneActivity.this, mCommitBtn);
        String url = RequestCode.post_TuiHuanHuo;
        int detailID = 0;

        if (myOrderDetailBean != null) {
            detailID = myOrderDetailBean.getDetailID();
        }
        String name = mRealNameEt.getText().toString().trim();
        try {
            name = URLEncoder.encode(name, "UTF-8");

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        String phone = mPhoneNumEt.getText().toString().trim();

        int type = 0;
        int checkedRadioButtonId = mRadioGroup.getCheckedRadioButtonId();
        if (R.id.rb_me_pay_2 == checkedRadioButtonId) {
            type = 1;
        } else if (R.id.rb_me_pay_3 == checkedRadioButtonId) {
            type = 2;
        }
        String pics = "";
        if (picSb.toString().length() > 5) {
            pics = picSb.toString();
        }
        String content = mContentEt.getText().toString().trim();
        try {
            content = URLEncoder.encode(content, "UTF-8");

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        String encodeStr = "&id=" + detailID + "&realName=" + name + "&mobile=" + phone + "&type=" + type + "&number=" + count + "&pics=" + pics + "&content=" + content;

        url += encodeStr;

        HttpRequestBean httpRequestBean = new HttpRequestBean(RequestCode.POSTEQUEST, url, this, WxremindBean.class, RequestCode.post_TuiHuanHuo);
        HttpHandleUtil.executeCommonPost(this, httpRequestBean);


        return "";
    }


    public boolean checkPhoneNum(String mobiles) {
        if (mobiles.length() != 11) {
            return false;
        }
        Pattern p = Pattern.compile("[1][34578]\\d{9}");

        Matcher m = p.matcher(mobiles);
        System.out.println(m.matches() + "---");
        return m.matches();

    }


    private boolean checkInfo() {
        String name = mRealNameEt.getText().toString().trim();
        if (TextUtils.isEmpty(name)) {
            CUtils.showToast("真实姓名不能为空");
            return false;
        }
        String phone = mPhoneNumEt.getText().toString().trim();
        if (TextUtils.isEmpty(phone)) {
            CUtils.showToast("手机号不能为空");
            return false;
        }
        if (!checkPhoneNum(phone)) {
            CUtils.showToast("手机号码格式验证错误，请重新输入");
            return false;
        }
        String describe = mContentEt.getText().toString().trim();

        if (TextUtils.isEmpty(describe)) {
            CUtils.showToast("描述内容不能为空");
            return false;
        }

        return true;
    }

    private void updatePics() {
        showProgressPopupWindow( mCommitBtn);
        String picUrl = RequestCode.PostUploadTuiHuanHuo;
        picUrl += "&memberMobile=" + memberID;
        mCommitBtn.setEnabled(false);
        final String finalPicUrl = picUrl;
        new Thread() {
            @Override
            public void run() {
                long start = System.currentTimeMillis();
                for (int i = 0; i < tempSelectBitmapList.size(); i++) {
                    String imagePath = tempSelectBitmapList.get(i).getImagePath();
                    if (!TextUtils.isEmpty(imagePath)) {
                        File picfile = new File(imagePath);
                        requestCount++;
                        uploadePic(picfile, finalPicUrl);
                    }
                }

                long end = System.currentTimeMillis();

            }
        }.start();

    }


    private synchronized void uploadePic(File picFile, String url) {

        UpLoadUtil upLoadUtil = new UpLoadUtil(url, picFile, new UpLoadUtil.ResultCallBack() {
            @Override
            public void getResult(UpLoadImage upLoadImage) {
                String resCode = upLoadImage.getResCode();
                if ("0000".equals(resCode)) {
                    picSb.append(upLoadImage.getResult().getUrlField() + ";");
                    picNums++;
                    int progress = (int) (((picNums*1f) / (tempSelectBitmapList.size()*1f))*100);
                    Message message = new Message();
                    message.what=PROGRESS;
                    message.arg1=progress;
                    handler.sendMessage(message);
                } else {
                    Message message = new Message();
                    message.arg1 = picNums;
                    message.what = PICERROR;
                    handler.sendMessage(message);
                }
                if (picNums == tempSelectBitmapList.size()) {

                    handler.sendEmptyMessage(PICSUCESS);
                }


            }
        });
        upLoadUtil.uploadFile(picFile, url);
    }

    @Override
    public void onSucess(SuccessBean sucessbean) {
        Object data = sucessbean.getData();
        if (mCommitpop != null) {
            mCommitpop.dismiss();
        }
        isTakePhoto=false;
        if (data instanceof WxremindBean) {
            WxremindBean resultData = (WxremindBean) data;
            if (resultData.isResult()) {
                CUtils.showToast(resultData.getMsg());
                handler.sendEmptyMessage(FINISH);
            } else {
                CUtils.showToast(resultData.getMsg());
            }
        }

    }

    @Override
    public void onError(ErrorBean errorBean) {
        if (mCommitpop != null) {
            mCommitpop.dismiss();
        }
        isTakePhoto=false;
        mCommitBtn.setEnabled(true);
        CUtils.showDataErrToast(this);
    }


    public class GridAdapter extends BaseAdapter {
        private LayoutInflater inflater;
        private int selectedPosition = -1;
        private boolean shape;

        public boolean isShape() {
            return shape;
        }

        public void setShape(boolean shape) {
            this.shape = shape;
        }

        public GridAdapter(Context context) {
            inflater = LayoutInflater.from(context);
        }

        public void update() {
            loading();
        }


        @Override
        public int getCount() {
            if (Bimp.getInstance().getTempSelectBitmap().size() == 5) {
                return 5;
            }
            return (Bimp.getInstance().getTempSelectBitmap().size() + 1);

        }

        public void setSelectedPosition(int position) {
            selectedPosition = position;
        }

        public int getSelectedPosition() {
            return selectedPosition;
        }

        @Override
        public Object getItem(int position) {
            return null;
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {

            convertView = inflater.inflate(R.layout.item_published_grida, parent, false);
            ImageView image = (ImageView) convertView.findViewById(R.id.item_grida_image);
            if (position == Bimp.getInstance().getTempSelectBitmap().size()) {
                image.setImageBitmap(BitmapFactory.decodeResource(getResources(), R.mipmap.icon_addpic_unfocused));
                //当有5张图片的时候
                if (position == 5) {
                    image.setVisibility(View.GONE);
                }
            } else {
                image.setImageBitmap(Bimp.getInstance().getTempSelectBitmap().get(position).getBitmap());
            }
            return convertView;
        }


        public void loading() {
            new Thread(new Runnable() {
                public void run() {
                    while (true) {
                        if (Bimp.max == Bimp.getInstance().getTempSelectBitmap().size()) {
                            Message message = new Message();
                            message.what = 1;
                            handler.sendMessage(message);
                            break;
                        } else {
                            Bimp.max += 1;
                            Message message = new Message();
                            message.what = 1;
                            handler.sendMessage(message);
                        }

                    }
                }
            }).start();
        }

    }

    private void showDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setMessage("检测到您的网络处于非wifi状态或非4g状态,上传图片将消耗一定的流量,是否继续?");
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                updatePics();
                dialog.dismiss();
            }
        });
        builder.show();
    }


    private void init() {
        pop = new PopupWindow(this);
        View view = getLayoutInflater().inflate(R.layout.item_popupwindows, null);
        ll_popup = (LinearLayout) view.findViewById(R.id.ll_popup);
        pop.setWidth(ViewGroup.LayoutParams.MATCH_PARENT);
        pop.setHeight(ViewGroup.LayoutParams.MATCH_PARENT);
        pop.setBackgroundDrawable(new BitmapDrawable());
        pop.setFocusable(true);
        pop.setOutsideTouchable(true);
        pop.setContentView(view);

        RelativeLayout parent = (RelativeLayout) view.findViewById(R.id.parent);
        Button bt1 = (Button) view
                .findViewById(R.id.item_popupwindows_camera);
        Button bt2 = (Button) view
                .findViewById(R.id.item_popupwindows_Photo);
        Button bt3 = (Button) view
                .findViewById(R.id.item_popupwindows_cancel);
        parent.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                pop.dismiss();
                ll_popup.clearAnimation();
            }
        });
        bt1.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                //拍照;
                photo();
                pop.dismiss();
                ll_popup.clearAnimation();
            }
        });
        bt2.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                //进入相册浏览界面;
                Intent intent = new Intent(ApplyServiceOneActivity.this, AlbumActivity.class);
                intent.putExtra("fromActivity", "ApplyServiceOneActivity");

                startActivity(intent);
                overridePendingTransition(R.anim.activity_translate_in, R.anim.activity_translate_out);
                pop.dismiss();
                ll_popup.clearAnimation();
            }
        });
        bt3.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                pop.dismiss();
                ll_popup.clearAnimation();
            }
        });
    }


    @Subscribe
    public void onEventMsg(MessageEvent msg) {
        if (adapter != null) {
            adapter.update();
        }
    }


    /**
     * 获取路径;
     *
     * @param s
     * @return
     */
    public String getString(String s) {
        String path = null;
        if (s == null)
            return "";
        for (int i = s.length() - 1; i > 0; i++) {
            s.charAt(i);
        }
        return path;
    }

    @Override
    protected void onRestart() {
        adapter.update();
        int measuredHeight = mScrollview.getMeasuredHeight();
        super.onRestart();
    }

    @Override
    protected void onResume() {
        super.onResume();
        adapter.update();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case TAKE_PICTURE:
                if (data != null) {
                    if (Bimp.getInstance().getTempSelectBitmap().size() < 5 && resultCode == RESULT_OK) {
                        try {
                            String fileName = String.valueOf(System.currentTimeMillis());
                            Bitmap bm = (Bitmap) data.getExtras().get("data");
                            File tempDir = new File(FileUtil.getImgFile(this), "tuihuan");
                            if (!tempDir.exists()) {
                                tempDir.mkdirs();
                            }
                            File tempPath = new File(tempDir, fileName + ".jpg");
                            FileOutputStream out = new FileOutputStream(tempPath);
                            bm.compress(Bitmap.CompressFormat.JPEG, 90, out);
                            out.flush();
                            out.close();
                            ImageItem takePhoto = new ImageItem();
                            takePhoto.setBitmap(bm);
                            takePhoto.setImagePath(tempPath.getAbsolutePath());
                            takePhoto.setSelected(true);
                            Bimp.getInstance().getTempSelectBitmap().add(takePhoto);
                            adapter.update();

                            for (int i = 0; i < Bimp.getInstance().getTempSelectBitmap().size(); i++) {
                                String imagePath = Bimp.getInstance().getTempSelectBitmap().get(i).getImagePath();
                            }

                        } catch (Exception e) {
                        }
                    }
                }


                break;
            case TAKE_CROP:


                break;
            case GETPIC:

                if (data != null) {
                    if (Bimp.getInstance().getTempSelectBitmap().size() < 5 && resultCode == RESULT_OK) {
                        try {
                            String fileName = String.valueOf(System.currentTimeMillis());
                            Bitmap bm = (Bitmap) data.getExtras().get("data");
                            File tempDir = new File(FileUtil.getImgFile(this), "tuihuan");
                            if (!tempDir.exists()) {
                                tempDir.mkdirs();
                            }
                            File tempPath = new File(tempDir, fileName + ".jpg");
                            FileOutputStream out = new FileOutputStream(tempPath);
                            bm.compress(Bitmap.CompressFormat.JPEG, 90, out);
                            out.flush();
                            out.close();
//                            FileUtils.saveBitmap(bm, fileName);
                            ImageItem takePhoto = new ImageItem();
                            takePhoto.setBitmap(bm);
                            takePhoto.setImagePath(tempPath.getAbsolutePath());
                            takePhoto.setSelected(true);
                            Bimp.getInstance().getTempSelectBitmap().add(takePhoto);
                            adapter.update();

                            for (int i = 0; i < Bimp.getInstance().getTempSelectBitmap().size(); i++) {
                                String imagePath = Bimp.getInstance().getTempSelectBitmap().get(i).getImagePath();
                            }

                        } catch (Exception e) {
                        }
                    }
                }




                break;

        }
    }


    /**
     * 进入照相的面;
     */
    public void photo() {
        isTakePhoto=true;
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED
                || ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            //申请MOUNT_UNMOUNT_FILESYSTEMS权限
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE}, PERMISSION_CAMERA);
        } else {
            Intent openCameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            startActivityForResult(openCameraIntent, TAKE_PICTURE);
        }

    }


    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        doNext(requestCode, grantResults);
    }


    private void doNext(int requestCode, int[] grantResults) {
        if (requestCode == PERMISSION_CAMERA) {
            if (grantResults.length > 0 && (grantResults[0] == PackageManager.PERMISSION_GRANTED)) {

                Intent openCameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                startActivityForResult(openCameraIntent, TAKE_PICTURE);

            } else {
                CUtils.showToast("请打开手机拍照权限后在操作");
            }
        }
    }


    private void processBitmap(ArrayList<ImageItem> tempSelectBitmapList) {

        for (int i = 0; i < tempSelectBitmapList.size(); i++) {

            String imagePath = tempSelectBitmapList.get(i).getImagePath();

            Bitmap newBitmap = compressBySize(imagePath, 320, 320);

            File tempDir = new File(FileUtil.getImgFile(this), "tuihuan");
            if (!tempDir.exists()) {
                tempDir.mkdirs();
            }
            String fileName = String.valueOf(System.currentTimeMillis());
            try {
                File tempPath = new File(tempDir, i + "" + fileName + ".jpg");

                FileOutputStream out = new FileOutputStream(tempPath);
                newBitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
                out.flush();
                out.close();
                tempSelectBitmapList.get(i).setImagePath(tempPath.getAbsolutePath());

            }catch (Exception e){
            }

            tempSelectBitmapList.get(i).setBitmap(newBitmap);

        }

    }

    private void showProgressPopupWindow(Button mCommitBtn) {

        View contentView = LayoutInflater.from(this).inflate(R.layout.progress_upload, null);
        mProgressbar = (ProgressBar) contentView.findViewById(R.id.pic_updata_progress);
        mProgressTv = (TextView) contentView.findViewById(R.id.tv_progress);

        mProgressbar.setMax(100);

        mProgresspop = new PopupWindow(contentView, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT, true);

        //点击空白处时，隐藏掉pop窗口
        mProgresspop.setTouchable(true);

        mProgresspop.setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.whitetranslucenthalf2)));

        contentView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mProgresspop.dismiss();
            }
        });


        //设置位置
        mProgresspop.showAtLocation(mCommitBtn, Gravity.BOTTOM|Gravity.CENTER_HORIZONTAL,0,0);//设置在屏幕中的显示位置

        // 设置好参数之后再show
//        mProgresspop.showAsDropDown(mBackLay);

    }



    //压缩图片尺寸
    public Bitmap compressBySize(String pathName, int targetWidth,
                                 int targetHeight) {
        BitmapFactory.Options opts = new BitmapFactory.Options();
        opts.inJustDecodeBounds = true;// 不去真的解析图片，只是获取图片的头部信息，包含宽高等；
        Bitmap bitmap = BitmapFactory.decodeFile(pathName, opts);
        // 得到图片的宽度、高度；
        float imgWidth = opts.outWidth;
        float imgHeight = opts.outHeight;
        // 分别计算图片宽度、高度与目标宽度、高度的比例；取大于等于该比例的最小整数；
        int widthRatio = (int) Math.ceil(imgWidth / (float) targetWidth);
        int heightRatio = (int) Math.ceil(imgHeight / (float) targetHeight);
        opts.inSampleSize = 1;
        if (widthRatio > 1 || widthRatio > 1) {
            if (widthRatio > heightRatio) {
                opts.inSampleSize = widthRatio;
            } else {
                opts.inSampleSize = heightRatio;
            }
        }
        //设置好缩放比例后，加载图片进内容；
        opts.inJustDecodeBounds = false;
        bitmap = BitmapFactory.decodeFile(pathName, opts);
        return bitmap;
    }



    @Override
    protected void onDestroy() {
        if(!isTakePhoto){
            Bimp.getInstance().getTempSelectBitmap().clear();
            Bimp.max = 0;
        }
        super.onDestroy();
    }
}
